<template>
  <div class="login_wrap">
    <div class="form_wrap">
      <el-form
        ref="tormRef"
        :model="loginData"
        label-width="100"
        class="demo-dynamic"
      >
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[
            {
              required: true,
              message: '此项为必填项',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model="loginData.username"></el-input>
        </el-form-item>

        <el-form-item
          label="密码"
          prop="password"
          :rules="[
            {
              required: true,
              message: '此项为必填项',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model="loginData.password" show-password></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" class="login_btn" @click="handleLogin"
        >登录</el-button
      >

      <!-- <p>{{ num }}</p> -->
    </div>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { loginApi } from "@/util/request";
export default {
  name: "login",
  setup() {
    const store = useStore();
    const router = useRouter();
    // const count = store.state.number.count;
    const data = reactive({
      loginData: {
        username: "admin",
        password: "123456",
      },
      // num: count,
    });

    const handleLogin = () => {
      //请求后台接口
      // 默认用户：admin/123456

      //我输入账号密码，后端响应给我关于这个账号的所有用户信息（token 、用户名、邮箱、角色等等）
      loginApi(data.loginData).then(res=> {       
        if (res.data){
          store.commit("setUserInfo", res.data);//全局状态管理
         
          localStorage.setItem("loginData", JSON.stringify(res.data));//存储到浏览器（磁盘）//JSON.stringify是把对象转成字符串
          store.commit('setUserInfo',localStorage.getItem("loginData")&&JSON.parse(localStorage.getItem("loginData"))
          );
          // store.state.uInfo.userInfo=localStorage.getItem("loginData")&&JSON.parse(localStorage.getItem("loginData"))

          console.log("11",res.data.token);
          console.log("22",store.state.uInfo.userInfo.token);
          
          
          console.log("11111111")
          //跳转到 /user 页面
          router.push({
            path: "/index",
          });
        }
      });
    };

    return {
      ...toRefs(data),
      handleLogin,
    };
  },
};
</script>

<style scoped>
.login_wrap {
  width: 100%;
  height: 100vh;
  background: rgb(56, 86, 139);
}
.form_wrap {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
  padding: 30px 50px;
  border-radius: 5px;
}
.login_btn {
  display: block;
  margin: 10px auto;
}
</style>